const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const redisStore = require('koa-redis')
const session = require('koa-generic-session')


const { REDIS_CONFIG } = require('./conf/db')
const { isProd } = require('./utils/env')
const { SESSION_SECRET_KEY } = require('./conf/secretKeys')

const { JWTSECRET } = require('./conf/constants')

const jwtKoa = require('koa-jwt')


const index = require('./routes/index')
const users = require('./routes/users')
const errorViweRoutes = require('./routes/view/error')
const user = require('./routes/view/user')
const userApiRouter = require('./routes/api/user')


// app.use(jwtKoa({
//   secret: JWTSECRET,
//   debug: true,
// }).unless({
//   path: [/^\/users\/login/], //自定义哪些目录忽略 jwt 验证
// }))

// error handler

let errorConfig = {}

if(isProd) {
  // errorConfig = {
  //   redirect:'/error'
  // }
}
onerror(app, errorConfig)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})




//session & cookies

app.keys = [SESSION_SECRET_KEY]
app.use(session({
  key: 'webo:sid',  // cookie 的name ,默认为 `koa.sid`
  prefix: 'webo:session:', // redis key的前缀 默认为 `koad:session:`
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000, //ms cookie 有效期

  },
  // ttl: 24* 60 * 60 * 1000, // redis 有效期
  store: redisStore({
    all: `${REDIS_CONFIG.host}:${REDIS_CONFIG.port}`
  })
}))


// routes ps: 一定要将路由放在session 配置的下面，否则取不到session
app.use(index.routes(), index.allowedMethods())
app.use(user.routes(), user.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(userApiRouter.routes(), userApiRouter.allowedMethods())
app.use(errorViweRoutes.routes(), errorViweRoutes.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
